#include <iostream>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>
#include <unistd.h>

using std::cerr;
using std::cin;
using std::cout;
using std::endl;

#define Size 1024

#define A_type 1
#define B_type 2

const char *pathname = "/home/ryan/Linux_code/linux/34_msg_test/test.cpp";
const int proj_id = 0x11223344;


struct my_msgbuf
{
    long mtype;         /* message type, must be > 0 */
    char mtext[Size]={0};   /* message data */
};

key_t getkey()
{
    key_t key = ftok(pathname, proj_id);
    if (key < 0)
    {
        cerr << "ftok error!" << endl;
        exit(1);
    }
    return key;
}

int main()
{
    
    key_t key = getkey();

    // 创建消息队列  不需要指定大小 shmget(key,4096*n,IPC_CREAT|IPC_EXCL|0666) 需要给定大小
    int msgid = msgget(key, IPC_CREAT | IPC_EXCL | 0666);

    struct my_msgbuf buf_snd,buf_rcv;

    buf_snd.mtype = A_type;
    read(0,buf_snd.mtext,sizeof buf_snd.mtext);

    int m = msgsnd(msgid,(void*)&buf_snd,sizeof buf_snd.mtext,0);
    cout<<"m:"<<m<<endl;

    int mm = msgrcv(msgid,(void*)&buf_rcv,sizeof buf_rcv.mtext,A_type,0);

    if(mm<0)
    {
        cerr<<"msgrcv error!"<<endl;
    }
    cout<<buf_rcv.mtext<<endl;

    // 删除消息队列
    int n = msgctl(msgid, IPC_RMID, nullptr);  //与 shm 类似，也是采用 nullptr
    if (n < 0)
    {
        cerr<<"delete msg error! error:"<<errno<<" strerror"<<strerror(errno)<<endl;
    }
    cout<<"delete msg"<<endl;
}